//
//  DdjPageViewController.m
//  ddj
//
//  Created by linqc on 17/7/1.
//  Copyright © 2017年 linqc. All rights reserved.
//

#import "ResultPageViewController.h"
#import "ContentPageViewController.h"
#import "Common.h"
#import "DictPageViewPlugin.h"

@interface ResultPageViewController ()<UIPageViewControllerDataSource, UIPageViewControllerDelegate> {
    NSMutableArray* allPage_;
    NSArray* info_;
    int64_t _platformViewId;
}

@end

@implementation ResultPageViewController

-(void)doTest {
    NSMutableArray* test = [[NSMutableArray alloc] init];
    NSMutableDictionary* d1 = [[NSMutableDictionary alloc] init];
    [d1 setValue:@"000" forKey:@"name"];
    [test addObject:d1];
    
    d1 = [[NSMutableDictionary alloc] init];
    [d1 setValue:@"111" forKey:@"name"];
    [test addObject:d1];
    
    d1 = [[NSMutableDictionary alloc] init];
    [d1 setValue:@"222" forKey:@"name"];
    [test addObject:d1];
    
    [self loadInfo:test];
}

-(void)doInit {
    if (allPage_ && allPage_.count) return;
    // todo:
   // [self doTest];
    
    [self refreshUI];
    
    self.view.backgroundColor = [Common colorWithHexString:@"#dddddd"];
}

-(void)setPlatformViewId:(int64_t)viewId {
    _platformViewId = viewId;
    for (NSUInteger i = 0; i < allPage_.count; ++i) {
        ContentPageViewController* vc = allPage_[i];
        if (vc) [vc setPlatformViewId:_platformViewId andTabIndex:i];
    }
}

-(void)loadInfo:(NSArray*)info {
    info_ = info;
    [self refreshUI];
}

-(void)refreshUI {
    NSUInteger dicCount = info_.count;
    allPage_ = [[NSMutableArray alloc] init];
    for (NSUInteger i = 0; i < dicCount; ++i) {
        ContentPageViewController* vc = [[ContentPageViewController alloc] initWithJson:(NSDictionary*)info_[i]];
        [vc setPlatformViewId:_platformViewId andTabIndex:i];
        [allPage_ addObject:vc];
    }
    
    [self changeTab:0];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.dataSource = self;
    self.delegate = self;

    [self doInit];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {

    if (completed && finished) {
        NSUInteger index = [self indexOfViewController:pageViewController.viewControllers[0]];
        if (index == NSNotFound) return;

        FlutterMethodChannel* channel = [DictPageViewPlugin getChannel];
        if (channel) {
            NSDictionary* args = @{
                    @"id": [NSNumber numberWithInt:_platformViewId],
                    @"tabIndex": [NSNumber numberWithInt:index]
            };
            [channel invokeMethod:@"onPageSelected" arguments:[Common objectToJson:args]];
        }
    }
}


-(UIViewController*)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSUInteger index = [self indexOfViewController:viewController];
    if (index == NSNotFound)
        return nil;
    
    index = [self getNextIndex:index isNext:YES];
    
    return [self viewControllerAtIndex:index];
}

-(NSUInteger)getNextIndex:(NSInteger)index isNext:(BOOL)isNext {
    int step = 1;
    if (!isNext)
    {
        step = -1;
    }
    
    int tempIndex = (int)index;

    int nextIndex = tempIndex + step;
    if (nextIndex == -1)
    {
        nextIndex = (int)allPage_.count - 1;
    }
    else if (nextIndex >= allPage_.count)
    {
        nextIndex = 0;
    }
    
    tempIndex = nextIndex;
    
    
    return tempIndex;
}

-(UIViewController*)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSUInteger index = [self indexOfViewController:viewController];
    if (index == NSNotFound)
        return nil;
    index = [self getNextIndex:index isNext:NO];
    return [self viewControllerAtIndex:index];
}

-(NSUInteger)indexOfViewController:(UIViewController*)vc {
    for(int i = 0; i < allPage_.count; ++i)
    {
        if ([self->allPage_[i] isEqual:vc]) {
            return i;
        }
    }
    
    return NSNotFound;
}

-(ContentPageViewController*)viewControllerAtIndex:(NSUInteger)index {
    return [allPage_ objectAtIndex:index];
}

-(void)loadUrl:(NSString*)url atIndex:(NSUInteger)index {
    ContentPageViewController* vc = [self viewControllerAtIndex:index];
    if (vc) {
        [vc loadUrl:url];
    }
}


-(void)changeTab:(NSUInteger)index {
    if (index < 0 || index >= (int)allPage_.count) return;
    
    ContentPageViewController *initialViewController = [self viewControllerAtIndex:index];
    NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
    [self setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    
    bool canScroll = allPage_.count > 1;
    [self enableScroll:canScroll];

    FlutterMethodChannel* channel = [DictPageViewPlugin getChannel];
    if (channel) {
        NSDictionary* args = @{
                @"id": [NSNumber numberWithInt:_platformViewId],
                @"tabIndex": [NSNumber numberWithInt:index]
        };
        [channel invokeMethod:@"onPageSelected" arguments:[Common objectToJson:args]];
    }
}

-(void)takePhotoAt:(int)index {
    if (index < 0 || index >= (int)allPage_.count) return;

    ContentPageViewController *vc = [self viewControllerAtIndex:index];
    if (vc) [vc takePhoto];
}

-(void)enableScroll:(BOOL)enable {
    UIScrollView* sv = [self findScrollView];
    if (sv != nil){
        sv.scrollEnabled = enable;
    }
}

-(UIScrollView *)findScrollView{
    
    UIScrollView*scrollView;
    
    for(id subview in self.view.subviews){
        if([subview isKindOfClass:UIScrollView.class]){
            scrollView=subview;
            break;
        }
    }
    
    return scrollView;
}



@end
